import { Component } from "react";
import { Homepage } from "../App";
import TDom from "../common/TDom";
import TClassesLoader from "./TClassesLoader";
import TMarkdownEditor from "./TMarkdownEditor";

const PageTitle = '课堂';

export default
class TClasses extends Component{
  constructor(props){
    super(props);

    this.state={
      pageName      : 'index',
      classes       : [],    // 课程列表
      selectedClass : '' ,   // 选中课程
    }

    this.classesUrl = `/${Homepage}/data/classes/classes.json`;

    this.handleClassesChanged = this.handleClassesChanged.bind(this);
    this.refresh = this.refresh.bind(this);
  }

  componentDidMount(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();
  }

  // 从服务器获取课程列表
  refresh(){
    
    TDom.getDataFromUrl(this.classesUrl, (json)=>{
      let classes = [];
      for(let key in json){
        classes.push(json[key]);
      }
      this.setState({
        classes : classes,
      })
    });

  }

  handleClassesChanged(event){

    if(event.target.id === 'md-editor'){
      this.setState({
        pageName : 'editor'
      })

      return;
    }

    const selectedClass = this.state.classes[event.target.id];

    document.title = `T+藏宝馆-${PageTitle}:${selectedClass.className}`;

    this.setState({
      pageName      : selectedClass.classId,
      selectedClass : selectedClass
    })

    console.log(`选中课程：`, selectedClass);
  }

  // 显示主页
  homepage(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();

    this.setState({ pageName:'index' });
  }

  _home(){
    return(
    <div className="body">
      <div>
        <button className='hlink' onClick={this.props.home}>T<sup>+</sup>藏宝馆:</button>
        <button className='hlink' onClick={this.refresh}>{`${PageTitle}`}</button>
        <button  id='md-editor' onClick={this.handleClassesChanged}>MD编辑器</button>
      </div>
      <div className="book-list">
        {this._renderClasses()}
      </div>
    </div>
    );
  }

  // 渲染课程列表
  _renderClasses(){
    const classes      = this.state.classes;

    return classes.map((item, key)=>
      <div className="book" key={key}>
        <img src={`/${Homepage}/${item.classCover}`} 
          alt={`/${Homepage}/${item.classCover}`}>
        </img>
        <button id={key} onClick={this.handleClassesChanged}>{item.className}</button>
      </div>
    );
  }

  render(){
    if(this.state.pageName === 'index'){
      return this._home();
    }
    else if(this.state.pageName === 'editor'){
      return <TMarkdownEditor home = {this.homepage.bind(this)}  ClassInfo={this.state.selectedClass}/>;
    }
    else{
      return <TClassesLoader 
        home = {this.homepage.bind(this)}
        ClassInfo={this.state.selectedClass}
      />
    }
  }
}